package co.yixiang.modules.user.service.impl;

import cn.hutool.core.util.StrUtil;
import co.yixiang.common.service.impl.BaseServiceImpl;
import co.yixiang.enums.BillDetailEnum;
import co.yixiang.enums.ShopCommonEnum;
import co.yixiang.exception.BadRequestException;
import co.yixiang.modules.user.domain.MonthlyManagementAward;
import co.yixiang.modules.user.domain.YxUser;
import co.yixiang.modules.user.domain.YxUserBill;
import co.yixiang.modules.user.service.MonthlyManagementAwardService;
import co.yixiang.modules.user.service.YxUserBillService;
import co.yixiang.modules.user.service.YxUserService;
import co.yixiang.modules.user.service.dto.MonthlyManagementAwardDto;
import co.yixiang.modules.user.service.dto.MonthlyManagementAwardQueryCriteria;
import co.yixiang.modules.user.service.mapper.MonthlyManagementAwardMapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import co.yixiang.dozer.service.IGenerator;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import co.yixiang.common.utils.QueryHelpPlus;
import co.yixiang.utils.ValidationUtil;
import co.yixiang.utils.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import org.springframework.data.domain.Pageable;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

import co.yixiang.domain.PageResult;
/**
* @author lsh
* @date 2021-05-12
*/
@Slf4j
@Service
@AllArgsConstructor
//@CacheConfig(cacheNames = "monthlyManagementAward")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class MonthlyManagementAwardServiceImpl extends BaseServiceImpl<MonthlyManagementAwardMapper, MonthlyManagementAward> implements MonthlyManagementAwardService {

    private final YxUserService yxUserService;
    private final YxUserBillService yxUserBillService;
    private final MonthlyManagementAwardMapper monthlyManagementAwardMapper;
    private final IGenerator generator;

    @Override
    //@Cacheable
    public PageResult<MonthlyManagementAwardDto> queryAll(MonthlyManagementAwardQueryCriteria criteria, Pageable pageable) {
        getPage(pageable);
        PageInfo<MonthlyManagementAward> page = new PageInfo<>(queryAll(criteria));
        return generator.convertPageInfo(page,MonthlyManagementAwardDto.class);
    }


    @Override
    //@Cacheable
    public List<MonthlyManagementAward> queryAll(MonthlyManagementAwardQueryCriteria criteria){
        return baseMapper.selectList(QueryHelpPlus.getPredicate(MonthlyManagementAward.class, criteria));
    }

    @Override
    //@Cacheable
    public List<MonthlyManagementAward> getManagementAward4monthList(int page, int limit, long uid, String month){
        Page<MonthlyManagementAward> pageModel = new Page<>(page, limit);
        List<MonthlyManagementAward> billDTOList = monthlyManagementAwardMapper.getManagementAward4monthList(pageModel,uid,month);
        return billDTOList;
    }


    @Override
    public void download(List<MonthlyManagementAwardDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (MonthlyManagementAwardDto monthlyManagementAward : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("用户手机号", monthlyManagementAward.getUserPhone());
            map.put("上级", monthlyManagementAward.getParentId());
            map.put(" enabled",  monthlyManagementAward.getEnabled());
            map.put("创建日期", monthlyManagementAward.getCreateTime());
            map.put(" updateTime",  monthlyManagementAward.getUpdateTime());
            map.put(" isDel",  monthlyManagementAward.getIsDel());
            map.put(" level",  monthlyManagementAward.getLevel());
            map.put("月份", monthlyManagementAward.getMonth());
            map.put("昵称", monthlyManagementAward.getNickname());
            map.put("微信头像地址", monthlyManagementAward.getHeadimgurl());
            map.put("团队总业绩", monthlyManagementAward.getTotalSum());
            map.put("应收管理奖金额", monthlyManagementAward.getReceivableSum());
            map.put("实收管理奖金额", monthlyManagementAward.getReceiptsSum());
            map.put("上级手机号", monthlyManagementAward.getParentUserPhone());
            map.put("上级微信昵称", monthlyManagementAward.getParentNickname());
            map.put("上级微信头像地址", monthlyManagementAward.getParentHeadimgurl());
            map.put("是否开启", monthlyManagementAward.getIsOpen());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    /**
     * 更新审核状态
     * @param resources MonthlyManagementAward
     */
    @Override
    public void doApprove(MonthlyManagementAward resources){
        log.info("Status============"+resources.getStatus());
        MonthlyManagementAward monthlyManagementAward = this.getById(resources.getId());
        if(!ShopCommonEnum.EXTRACT_0.getValue().equals(monthlyManagementAward.getStatus())){
            throw new BadRequestException("该申请已经处理过啦！");
        }
        YxUser user =yxUserService.getById(resources.getUid());
        BigDecimal receiptsSum =new BigDecimal("0");
        if(resources.getReceiptsSum().compareTo(new BigDecimal("0")) ==1){
            receiptsSum =resources.getReceiptsSum();
            BigDecimal usertotalSum =user.getNowMoney().add(receiptsSum);
            yxUserService.incMoney(user.getUid(),receiptsSum);
            yxUserService.incBrokeragePrice(receiptsSum,user.getUid());
            yxUserBillService.income(user.getUid(),"14", BillDetailEnum.CATEGORY_1.getValue(),
                    BillDetailEnum.TYPE_2.getValue(),receiptsSum.doubleValue(),usertotalSum.doubleValue(), "月管理奖","");
            System.out.println(user.getLevel() + "级用户" + user.getUid()
                    + "：《月管理奖》" + receiptsSum + "元");
            monthlyManagementAward.setStatus(1);
            this.saveOrUpdate(monthlyManagementAward);
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式

        log.info("time2222============"+df.format(new Date()));
    }
}
